package org.webdb;

import org.apache.log4j.Logger;
import org.spawndb.util.PropUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

public class WebContextListener implements ServletContextListener {


    private static HashMap<String,String> params = new HashMap<String,String>();
    private static Logger log = Logger.getLogger("org.webdb.DBWebContextListener");


    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        populateDefaultValues(context);
        Enumeration en = context.getInitParameterNames();
        while(en.hasMoreElements()){
            String paramName = (String) en.nextElement();
            params.put(paramName,context.getInitParameter(paramName));
        }
        //load context properties
        loadContextProperties();
    }

    public static void loadProperties(String path) {
        File propsFile = new File(path);
        if(propsFile.exists()){
        	Properties props = null;
        	try {
				props = PropUtils.loadProperties(propsFile);
			} catch (IOException e) {
				e.printStackTrace();
			}

			if(props != null){
				Enumeration<Object> e = props.keys();
				while(e.hasMoreElements()){
					String key = (String) e.nextElement();
					params.put(key, props.getProperty(key));
				}
			}
        }
    }

    public static void loadContextProperties() {
        loadProperties(getParameter("context.home")+"/conf/db.properties");
    }


    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Stopping "+ getParameter("context.name"));

    }

    public static String getParameter(String paramName){
        String value = params.get(paramName);
        if (value==null)
                value = System.getProperty(paramName);
        return value;
    }

    public static void setParameter(String paramName, String paramValue){
        params.put(paramName,paramValue);
    }


    private void populateDefaultValues(ServletContext context){
        String appRoot= context.getRealPath("/");
        try {
            final File rootPath = new File(appRoot);
            appRoot=rootPath.getCanonicalPath().replace('\\','/');
            params.put("context.name",rootPath.getName());
            System.setProperty(rootPath.getName()+".home",appRoot);
        } catch (IOException e) {
            e.printStackTrace();
        }
        params.put("context.home",appRoot);
        params.put("context.tmp.dir","/tmp");

    }

}